package com.xuzimian.global.demo.spring.security.oauth2.resource.controller;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

@Component
public class MyLogoutSuccessHandle implements LogoutSuccessHandler {
    private final Logger logger = LoggerFactory.getLogger(MyLogoutSuccessHandle.class);

    @Autowired
    private TokenStore tokenStore;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        Optional<OAuth2AccessToken> tokenOptional = getToken(request);

        if (!tokenOptional.isPresent()) {
            logger.error("access token 获取失败");
            return;
        }

        tokenStore.removeAccessToken(tokenOptional.get());
        logger.debug("成功退出");
    }


    private Optional<OAuth2AccessToken> getToken(HttpServletRequest request) {
        //从参数中获取
        String token = request.getParameter("access_token");
        if (StringUtils.isNotBlank(token)) {
            OAuth2AccessToken oAuth2AccessToken = this.tokenStore.readAccessToken(token.trim());
            if (oAuth2AccessToken != null) {
                return Optional.of(oAuth2AccessToken);
            }
        }

        //从头部中获取
        token = request.getHeader("authorization");
        if (StringUtils.isBlank(token)) {
            return Optional.empty();
        }
        String[] arr = StringUtils.split(token, " ");
        if (arr == null || arr.length != 2) {
            return Optional.empty();
        }
        token = arr[1];
        OAuth2AccessToken oAuth2AccessToken = this.tokenStore.readAccessToken(token.trim());
        return Optional.ofNullable(oAuth2AccessToken);
    }

}
